package top.withwings.bonus.bonus.repo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class ExpirationCloseAttachmentRepo {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Integer findByGood(int goodId){
        String sql = "select rule_Id from expiration_close_attachment where good_id = ?";
        try{
            return jdbcTemplate.queryForObject(sql,Integer.class,goodId);
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    public void attach(int ruleId, int... goodIds){

        String sql = "insert into expiration_close_attachment(good_id,rule_Id) values (?,?) ";

        List<Object[]> args = new ArrayList<>();

        for (int goodId : goodIds) {
            args.add(new Object[]{goodId,ruleId});
        }

        jdbcTemplate.batchUpdate(sql,args);

    }

    public void detach(int... goodIds){

        String sql = "delete from expiration_close_attachment where good_id = ? ";

        List<Object[]> args = new ArrayList<>();

        for (int goodId : goodIds) {
            args.add(new Object[]{goodId});
        }

        jdbcTemplate.batchUpdate(sql,args);

    }

    public boolean hasAttachment(int ruleId) {

        String sql = " select count(*) from expiration_close_attachment where rule_Id = ?";

        return jdbcTemplate.queryForObject(sql, Integer.class,ruleId)>0;

    }
}